// http://127.0.0.1:9981/hulu-obj-data/color-glb/base_basic_shaded.glb

import BackBtn from '@components/globalComponents/BackBtn';
import React, { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

function HuluBabyGLB(): React.ReactElement {
  const mountRef = useRef<HTMLDivElement>(null);
  const modelRef = useRef<THREE.Object3D>(null);
  const [isPlaying, setIsPlaying] = useState<boolean>(true);

  useEffect(() => {
    if (!mountRef.current) return;

    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xeeeeee);

    const camera = new THREE.PerspectiveCamera(
      75,
      mountRef.current.clientWidth / mountRef.current.clientHeight,
      0.1,
      1000,
    );
    // 将相机位置下移并拉远，使模型居中偏下且缩小
    camera.position.set(0, 0.5, 5);

    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(
      mountRef.current.clientWidth,
      mountRef.current.clientHeight,
    );
    mountRef.current.appendChild(renderer.domElement);

    const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
    directionalLight.position.set(5, 5, 5);
    scene.add(directionalLight);

    const loader = new GLTFLoader();
    loader.load(
      'http://127.0.0.1:9981/hulu-obj-data/color-glb/base_basic_shaded.glb',
      (gltf) => {
        // 将模型整体下移，使其居中偏下
        gltf.scene.position.y = -1.5;
        // 可选：统一缩放模型使其更小
        gltf.scene.scale.set(0.2, 0.2, 0.2);
        scene.add(gltf.scene);

        // 保存模型引用
        modelRef.current = gltf.scene;
      },
      undefined,
      (error) => {
        console.error('加载 GLB 模型失败:', error);
      },
    );

    const controls =
      new (require('three/examples/jsm/controls/OrbitControls').OrbitControls)(
        camera,
        renderer.domElement,
      );
    controls.enableDamping = true;

    // 动画时间计数器
    let animationTime = 0;

    const animate = () => {
      requestAnimationFrame(animate);
      controls.update();

      // 如果动画正在播放且模型已加载
      if (isPlaying && modelRef.current) {
        animationTime += 0.016; // 近似于60fps

        // 摇头动画 - 沿着Y轴旋转
        const headRotation = Math.sin(animationTime * 1.5) * 0.2; // 角度控制在±0.2弧度
        modelRef.current.rotation.y = headRotation;

        // 尝试查找手臂并添加摆手动画
        // 由于我们不知道模型的确切结构，我们可以遍历子节点或尝试直接查找
        const leftArm =
          findObjectByName(modelRef.current, 'leftArm') ||
          findObjectByName(modelRef.current, 'armLeft') ||
          findObjectByName(modelRef.current, 'left_arm');
        const rightArm =
          findObjectByName(modelRef.current, 'rightArm') ||
          findObjectByName(modelRef.current, 'armRight') ||
          findObjectByName(modelRef.current, 'right_arm');

        // 为左手臂添加摆动动画 - 沿着Z轴旋转，与摇头有相位差
        if (leftArm) {
          leftArm.rotation.z =
            Math.sin(animationTime * 1.2 + Math.PI / 2) * 0.3; // 相位差为π/2，方向相反
        }

        // 为右手臂添加摆动动画 - 沿着Z轴旋转，与左手臂相反
        if (rightArm) {
          rightArm.rotation.z = Math.sin(animationTime * 1.2) * 0.3;
        }
      }

      renderer.render(scene, camera);
    };

    // 递归查找指定名称的对象
    const findObjectByName = (
      parent: THREE.Object3D,
      name: string,
    ): THREE.Object3D | null => {
      if (parent.name.toLowerCase().includes(name.toLowerCase())) {
        return parent;
      }

      for (const child of parent.children) {
        const found = findObjectByName(child, name);
        if (found) {
          return found;
        }
      }

      return null;
    };

    animate();

    const handleResize = () => {
      if (!mountRef.current) return;
      camera.aspect =
        mountRef.current.clientWidth / mountRef.current.clientHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(
        mountRef.current.clientWidth,
        mountRef.current.clientHeight,
      );
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (mountRef.current && renderer.domElement) {
        mountRef.current.removeChild(renderer.domElement);
      }
      renderer.dispose();
    };
  }, [isPlaying]);

  // 控制动画播放
  const playAnimation = () => {
    setIsPlaying(true);
  };

  // 控制动画暂停
  const pauseAnimation = () => {
    setIsPlaying(false);
  };

  return (
    <div>
      {/* 返回首页按钮 */}
      <div
        style={{ position: 'absolute', top: '16px', left: '16px', zIndex: 10 }}
      >
        <BackBtn />
      </div>
      {/* 动画控制按钮 */}
      <div
        style={{
          position: 'absolute',
          bottom: '20px',
          left: '50%',
          transform: 'translateX(-50%)',
          display: 'flex',
          gap: '10px',
          padding: '10px',
          backgroundColor: 'rgba(0, 0, 0, 0.3)',
          borderRadius: '8px',
          zIndex: 10,
        }}
      >
        <button
          type="button"
          onClick={pauseAnimation}
          style={{
            padding: '8px 16px',
            backgroundColor: '#ff6b35',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
          }}
        >
          暂停
        </button>
        <button
          type="button"
          onClick={playAnimation}
          style={{
            padding: '8px 16px',
            backgroundColor: '#4caf50',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            cursor: 'pointer',
          }}
        >
          播放
        </button>
      </div>
      <div ref={mountRef} style={{ width: '100%', height: '100vh' }} />
    </div>
  );
}

export default HuluBabyGLB;
